package com.itheima.thread;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

public class ThreadSocket implements Runnable {
    private Socket socket = null;
    public ThreadSocket(Socket accept) {
        this.socket = accept;
    }

    @Override
    public void run() {

        try {
            //创建网络输入流，接受发送过来的数据
            InputStream is = socket.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

            //创建本地输出流，将接收到的数据写入本地文件
            BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream("day15_inter\\"+ UUID.randomUUID()+".png"));
            int b ;
            //循环写入
            while ((b = bis.read())!=-1){
                bw.write(b);
            }
            bw.close();

            //接收完成，发送反馈
            OutputStream os = socket.getOutputStream();
            BufferedWriter fankui = new BufferedWriter(new OutputStreamWriter(os));
            fankui.write("上传成功");
            fankui.flush();
            socket.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket!= null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
